<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use app\model\DeptModel;
use app\model\CompanyModel;
use think\Db;
use app\common\BaseController;
use app\model\UserModel;

class Dept extends BaseController
{
    public function _initialize(){
        $this->request = Request::instance();
        $this->noNeedLogin = ['session_set',''];
    }

    public function add_post(Request $request){
        $companyid = trim($this->request->param('companyid'));
        $name = trim($this->request->param('name'));

        if(empty($companyid)){
            return toJson(['message'=>'公司ID不能为空','code'=>'400']);
        }

        if(empty($name)){
            return toJson(['message'=>'部门名称不能为空','code'=>'400']);
        }

        $companyData = CompanyModel::where('id','eq',$companyid)->find();
        if(empty($companyData)){
            return toJson(['message'=>'公司不存在','code'=>'400']);
        }

        $deptData = DeptModel::where('companyid','eq',$companyid)->where('name','eq',$name)->find();
        if($deptData){
            return toJson(['message'=>'该部门已存在','code'=>'400']);
        }
        
        $deptModel = new DeptModel;
        $deptModel->companyid = $companyid;
        $deptModel->name = $name;
        $deptModel->createtime = time();
        $deptModel->save();

        if( $deptModel->id > 0 ){
            return toJson(['message'=>'新增部门成功','code'=>'200']);

        }else{
            return toJson(['message'=>'新增部门出错，请联系客服！','code'=>'400']);
        }

    }

    public function edit_post(Request $request){
        $id = trim($this->request->param('id'));
        $name = trim($this->request->param('name'));

        if(empty($id)){
            return toJson(['message'=>'部门ID不能为空','code'=>'400']);
        }

        if(empty($name)){
            return toJson(['message'=>'部门名称不能为空','code'=>'400']);
        }


        $deptData = DeptModel::where('id','eq',$id)->find();
        if(empty($deptData)){
            return toJson(['message'=>'部门不存在','code'=>'400']);
        }

        $existName = DeptModel::where('companyid','eq',$deptData->companyid)->where('name','eq',$name)->find();

        if($existName){
            return toJson(['message'=>'该部门已存在','code'=>'400']);
        }

        $deptData->name = $name;
        $deptData->save();

        return toJson(['message'=>'修改部门成功','code'=>'200']);

    }

    public function delete_post(Request $request){
        $id = trim($this->request->param('id'));
        $type = trim($this->request->param('type'));//dept
        $companyid = trim($this->request->param('companyid'))?:$this->user->companyid;

        if(empty($id)){
            return toJson(['message'=>'部门ID不能为空','code'=>400]);
        }

        $deptData = DeptModel::where('id','eq',$id)->find();
        if(!$deptData){
            return toJson(['message'=>'部门不存在','code'=>'400']);
        }

        $where = 'deptid = '.$id.' and companyid = '.$companyid;
        if($type == 'dept'){
           $data = [
            'deptid' =>  0,
            'roleid' => 0

            ];
        }else{
           $data = [
            'companyid' => 0,
            'deptid' =>  0,
            'roleid' => 0
            ];
        }

        $delalldept_user = $this->update('user', $where, $data);

        $deptData->delete();

        return toJson(['message'=>'删除部门成功','code'=>'200']);
    }

    public function getlist_get(Request $request){
        $companyid = trim($this->request->param('companyid'))?:$this->user->companyid;
        $page = trim($this->request->param('page'));
        $pagesize = trim($this->request->param('pagesize'));
        $keyword = trim($this->request->param('keyword'));
        $type = $this->request->param('type'); //link vis
        $where_type = $type=='link'?'is_security  = 0':'1=1';
        $page = empty($page) ? 1 : $page;
        $pagesize = empty($pagesize) ? 10 : $pagesize;
        
        $where = $keyword ? ":name like %".$keyword."%" : '1=1';
// where('is_security != 1')
        $deptList = DeptModel::where($where)->where($where_type)->where('companyid','eq',$companyid)->where('deleteTime is null')->page($page,$pagesize)->select();
        $deptList = collection($deptList)->toarray();
        
        if($type=='link'){

            //部门受访人是否有
            $true_deptid = [];
            if(count($deptList)>0){
                $check_Interviewees = array_column($deptList,'id');

                foreach ($check_Interviewees as $key => $value) {
                    # code...
                    $check = $this->find('view_user','Interviewees = 1 and deptid = '.$value);
                    if($check){array_push($true_deptid, $value);}
                }
            }

            if(count($true_deptid)>0){
                $true_deptid = implode($true_deptid, ",");
                $deptList = DeptModel::where('id in ('.$true_deptid.')')->where('deleteTime is null')->page($page,$pagesize)->select();
            }else{
                // $deptList = [
                //     "id"=> 0,
                //     "companyid"=> 0,
                //     "name"=> "当前无受访人接待",
                //     "createtime"=> NULL,
                //     "is_security"=> 0,
                //     "status"=> 1,
                // ];
            }
        }
        return toJson(['message'=>'获取部门列表成功','code'=>'200','data'=>$deptList]);
    }
    
    public function info(){
		$deptid = trim($this->request->param('id'));
		$page = trim($this->request->param('page'));
		$pagesize = trim($this->request->param('pagesize'));
		$keyword = trim($this->request->param('keyword'));
		
		 $page = empty($page) ? 1 : $page;
		$pagesize = empty($pagesize) ? 10 : $pagesize;
		
		$where = $keyword ? ":name like %".$keyword."%" : '1=1';
		
		$deptList = Db::table('view_company_dept')->where('id',$deptid)->page($page,$pagesize)->find();
		
		return toJson(['message'=>'获取部门详情成功','code'=>'200','data'=>$deptList]);
	}

    public function join_post(){
        $uid = trim($this->request->param('uid'));
        $deptid = trim($this->request->param('deptid'));
        $companyid = trim($this->request->param('companyid'));

        //$userData = UserModel::where('id','eq',$uid)->where('companyid','eq',$this->user->companyid)->field('id,deptid')->find();
        $userData = UserModel::where('id','eq',$uid)->find();
        if(empty($userData)){
            return toJson(['message'=>'用户不存在','code'=>400]);
        }

        if($userData->deptid == $deptid){
            return toJson(['message'=>'用户已经是该部门员工了','code'=>400]);            
        }

        $find_deptinfo =$this->find('view_company_dept','id = '.$deptid);
        if(!empty($companyid)){
            $userData->companyid = $companyid;
            $userData->deptid = $deptid;
            if($userData->roleid == 0 || $userData->roleid == NULL){
                $userData->roleid = 4;
                if($find_deptinfo['is_security'] ==1){
                    $userData->roleid = 6;
                }
            }

            $result = $userData->save();
            if( $result === false ){
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }

            return toJson(['message'=>'员工加入部门成功','code'=>200]);
        }
        
        if($userData->roleid == 0 || $userData->roleid == NULL){
            $userData->roleid = 4;
            }
        if($find_deptinfo['is_security'] ==1){
            $userData->roleid = 6;
            }else{
            $userData->roleid = 4; 
            }
        $userData->deptid = $deptid;
        $userData->companyid = $find_deptinfo['companyid'];
        $result = $userData->save();

        if( $result === false ){
            return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }
        $this->find('view_user','id = '.$uid);
        //$this->member_integral(,10,'add');
        return toJson(['message'=>'员工加入部门成功','code'=>200]);
    }




    public function manager_post(){
        $uid = trim($this->request->param('uid'));
        $deptid = trim($this->request->param('deptid'));

        $userData = UserModel::where('id','eq',$uid)
                                ->where('companyid','eq',$this->user->companyid)
                                ->where('deptid','eq',$deptid)
                                ->field('id,deptid')
                                ->find();
        if(empty($userData)){
            return toJson(['message'=>'用户不存在','code'=>400]);
        }

        $oldUserData = UserModel::where('companyid','eq',$this->user->companyid)
                                ->where('deptid','eq',$deptid)
                                ->where('roleid','eq',3)
                                ->field('id,deptid')
                                ->find();
        
        if($oldUserData){
            $oldUserData->startTrans();
            $oldUserData->roleid = 4;
            $result = $oldUserData->save();
            
            if($result === false ){
                $oldUserData->rollBack();
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
            }

            $userData->startTrans();
            $userData->roleid = 3;
            $result = $userData->save();

            if($result === false ){
                $oldUserData->rollBack();
                $userData->rollBack();
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
            }

            $oldUserData->commit();
            $userData->commit();
        }
        return toJson(['message'=>'更换成功','code'=>200]);  
    }
    /**
     * 删除部门用户
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-09-16T11:16:41+0800
     * @LastTime     2020-09-16T11:16:41+0800
     * @return       [type]                       [description]
     */
    public function deldeptuser(){
        $uid = trim($this->request->param('uid'));
        $deptid = trim($this->request->param('deptid'));
        $companyid = trim($this->request->param('companyid'))?:$this->user->companyid;
        $type = trim($this->request->param('type')); //1-移出部门 //c-自身移出公司and部门

        if($type=='c'){
            $data = [
                'deptid' => 0,
                'companyid' => 0,
                'roleid' => 0,
            ];
            $res = $this->update('user','id = '.$this->uid,$data);
            return toJson(['message'=>'成功退出公司','code'=>200]);
        }
        if($type==1){
            $data = [
                'deptid' => 0,
                'roleid' => 4
            ];
        }else{
            $data = [
                'deptid' => 0,
                'companyid' => 0,
                'roleid' => 0
            ];
        }
        //是否为保安部门
        // $check_is = $this->find('view_company_dept','id = '.$deptid.' and companyid = '.$companyid);
        // if(@$check_is['is_security'] ==1){
        //     $data['roleid'] = 6;
        //     $data['']
        // }

        $where = 'id in ('.$uid.')';
        $res = $this->update('user', $where, $data);
        return toJson(['message'=>'成功删除该部门用户','code'=>200]);  

    }



}
